import type { CommentPlaylistReponse, PlaylistItem } from "@/services/type";
import { defineStore } from "pinia";
import { ref, watch } from "vue";
import { songUrlApi, lyricApi, commentSongApi } from "@/services" // 歌曲url接口
import type { SongUrlResponse } from "@/services/type"

export const useMusicStore = defineStore('music', () => {
  const loading = ref(false) // 加载中
  const historySearch = ref<string[]>([]) // 历史搜索列表数据
  const currentIndex = ref(-1) // 当前播放的歌曲下标
  const songsList = ref<PlaylistItem[]>([]) // 待播放的歌曲列表
  const canplay = ref(false) // 标识 可以播放
  const playStatus = ref(false) // 播放或暂停状态
  const currentTime = ref(0) // 歌曲当前播放时间
  const duration = ref(0) // 歌曲总时长
  const playform = ref(0) // 播放方式 0 顺序 1 逆序 2 单曲
  const song = ref<SongUrlResponse | null>(null) // 歌曲url信息
  const lyric = ref('') // 歌词
  const comment = ref<CommentPlaylistReponse>()

  // 创建一个audio
  const audio = uni.createInnerAudioContext();

  // 改变loading
  const changeLoading = (bol: boolean) => {
    loading.value = bol
  }
  // 添加或者删除历史搜索
  const changeHistorySearch = (i: string | number) => {
    // 判断传入的数据的数据类型
    switch (typeof i) {
      // 如果为字符串
      case 'string':
        // 判断传入的是否在数组里面了
        const index = historySearch.value.findIndex(v => v === i)
        if (index > -1) {
          // 在里面删除这一项
          historySearch.value.splice(index, 1)
        }
        // 往最前面添加这一项
        historySearch.value.unshift(i)
        break
      case 'number':
        // 如果传入了数字删除全部
        historySearch.value = [] as string[]
        break
      default:
        console.log('参数类型错误!')
    }

  }
  // 跳转页面
  const toPage = <T>(path: string, data = {} as T) => {
    const url = path + Object.entries(data as {}).reduce((res, item): string => {
      return res + item[0] + '=' + item[1] + '&'
    }, '?').slice(0, -1)
    // console.log(url)
    uni.navigateTo({ url })
  }
  // 添加歌曲列表
  const changeSongsList = (song: PlaylistItem | PlaylistItem[]) => {
    canplay.value = true
    // 播放这首歌
    if (Array.isArray(song)) {
      // 如果传入的是一个数组
      // 直接将播放列表替换掉
      songsList.value = song
      // 并且下标重置为0
      currentIndex.value = 0
    } else {
      // 传入的是一个歌曲
      // 查找下标
      const index = songsList.value.findIndex(v => v.id === song.id)
      if (index > -1) {
        // 如果找到了
        // 直接改变当前播放下标
        if (song.id === songsList.value[currentIndex.value].id) {
          // 跳到播放器页面
          currentIndex.value = index
          return
        }
        currentIndex.value = index
      } else {
        // 没有找到下标
        // 往最上面添加一项
        songsList.value.unshift(song)
        // 并且改变下标为0
        currentIndex.value = 0
      }
    }
    getUrl()
  }
  // 点击添加歌曲
  const onClickPlaySong = (song: PlaylistItem | undefined | PlaylistItem[]) => {
    if (!song) return
    // 添加音乐
    changeSongsList(song)
    // 跳到播放器页面
    toPage('/pages/player/player')
  }
  // 设置audio的src
  const setAudioSrc = (src: string) => {
    audio.src = src
  }
  // 处理时间
  const formatTime = (time: number) => {
    const h = time / 60 / 60 >> 0
    const m = time / 60 % 60 >> 0
    const s = time % 60 >> 0
    return h > 0 ? String(h).padStart(2, '0') + ':' : '' + String(m).padStart(2, '0') + ':' + String(s).padStart(2, '0')
  }
  // 改变播放方式
  const changePlayform = () => {
    playform.value = playform.value === 2 ? 0 : playform.value + 1
    audio.loop = playform.value === 2
  }
  // 切换歌曲
  const switchSong = (n: number) => {
    canplay.value = true
    if (playform.value) {
      currentIndex.value = Math.floor(Math.random() * songsList.value.length)
    } else {
      currentIndex.value += n
      // console.log(currentIndex.value)
      if (currentIndex.value < 0) currentIndex.value = songsList.value.length - 1
      if (currentIndex.value >= songsList.value.length) currentIndex.value = 0
    }
    getUrl()
  }
  // 获取歌曲url 和 歌词
  const getUrl = async () => {
    try {
      // 显示加载中
      changeLoading(true)
      // 调接口获取数据
      const id = songsList.value[currentIndex.value].id
      const res = await songUrlApi(id)
      const lyricRes = await lyricApi(id)
      // const commentRes = await commentSongApi(id)
      // 接受数据
      // detail.value = res.playlist
      // playlist.value = res.playlist.tracks
      // console.log(commentRes)

      if (res.code === 200) {
        song.value = res
        if (song.value.data[0].url) {
        // console.log(111)
          setAudioSrc(song.value.data[0].url)
        } else {
          audio.pause()
          uni.showToast({
            title: '暂无歌曲资源, 请稍后重试...',
            icon: 'error'
          })
        }
      }
      if (lyricRes.code === 200) {
        lyric.value = lyricRes.lrc.lyric
      }
      // if (commentRes.code === 200) {
      //   comment.value = commentRes
      // }
      // 隐藏加载中
      changeLoading(false)
    } catch (error) {
      console.log(error)
    }
  }
  const changeCanplay = (bol: boolean) => {
    canplay.value = bol
  }
  // 获取歌曲评论
  const getSongComment = async () => {
    // 当前没有可以播放的歌曲
    if (currentIndex.value === -1) return
    try {
      // 显示加载中
      loading.value = true
      const id = songsList.value[currentIndex.value].id
      // 调接口
      const res = await commentSongApi(id)
      console.log(res)
      // 返回码是200成功
      if (res.code === 200) {
        comment.value = res
      }
      // 隐藏加载中
      loading.value = false
    } catch (error) {
      console.log(error)
    }
  }
  // 删除歌曲列表的歌曲
  const removeSong = (song: PlaylistItem | undefined) => {
    // 没有接受完毕
    if (!song) return
    // 判断是否为当前播放的音乐
    const index = songsList.value.findIndex(v => v.id === song.id)
    // 如果没有在播放列表中找到
    if (index === -1) return
    // 如果是当前播放的音乐
    if (index === currentIndex.value) {
      // 切换歌曲
      switchSong(1)
    }
    // 不是正在播放的音乐直接删除
    songsList.value.splice(index, 1)
    // 如果删除的是正在播放之前的歌曲
    if (index < currentIndex.value) {
      // 下标减一
      currentIndex.value--
    }
  }
  const clearSongsList = () => {
    // 清空播放列表
    songsList.value = []
    // 重置播放下标
    currentIndex.value = -1
    // 重置播放src
    audio.src = ''
  }

  // 播放开始事件
  audio.onPlay(() => {
    // console.log('开始播放了')
    playStatus.value = true
    // console.log(playStatus.value)
  })
  // 播放暂停事件
  audio.onPause(() => {
    playStatus.value = false
    // console.log(playStatus.value)
  })
  // 播放时间更新事件
  audio.onTimeUpdate(() => {
    // console.log(111, 208)
    if (!canplay.value) return
    currentTime.value = audio.currentTime
    duration.value = audio.duration
  })
  // 播放自然结束事件
  audio.onEnded(() => {
    switchSong(1)
  })
  audio.onCanplay(() => {
    currentTime.value = audio.currentTime
    duration.value = audio.duration
  })

  // 监听变量canplay 是否开启监听可以播放事件
  watch(canplay, () => {
    if (canplay.value) {
      audio.autoplay = true
      // audio.onCanplay(audio.play)
    }
  })

  return {
    loading,
    changeLoading,
    changeHistorySearch,
    historySearch,
    toPage,
    changeSongsList,
    songsList,
    currentIndex,
    onClickPlaySong,
    setAudioSrc,
    playStatus,
    audio,
    currentTime,
    duration,
    formatTime,
    changePlayform,
    switchSong,
    playform,
    song,
    getUrl,
    canplay,
    changeCanplay,
    lyric,
    comment,
    getSongComment,
    removeSong,
    clearSongsList
  }
}, {
  persist: {
    storage: sessionStorage,
    pick: ['historySearch', 'currentIndex', 'songsList'],
  },
})
